library(data.table)
library(tidyverse)
library(Cairo)
theta <- seq(0,1, 0.01)

theme_set(theme_bw())
theme_update(panel.grid = element_blank(),
             panel.border = element_blank(),
             axis.text = element_text(size = 14, color = "gray40"),
             axis.line = element_line(size = 1, color = "gray40"),
             axis.ticks = element_line(size = 1, color = "gray40"),
             axis.title =element_text(face="italic", family = "serif", size = 24),
             legend.position = "none",
             plot.margin=grid::unit(c(5,5,2,2), "mm"))
lwdth <- 1.5
color_scale_values <- c('#f0f0f0','#bdbdbd','#636363')#c("#e34a33", "#43a2ca", "#78c679")

B <- 10.1
h <- function(c) {
  case_when(c <= 0 ~ 1,
            c >= 1 ~ 0,
            TRUE ~ 1 - sqrt(c))
  } 

f <- function(theta, s) {
  theta * h(s)
}

dt <- tibble(theta = theta) %>% 
  mutate(
    s_hlt = B*(.75 - .5*theta)/sum(theta),
    s_uni = B/n(),
    s_sck = B*(.25 + .5*theta)/sum(theta)) %>% 
  pivot_longer(cols = starts_with("s"), names_to = "policy", values_to = "s") %>% 
  mutate(f = f(theta, s),
         policy = factor(policy, levels = c("s_hlt", "s_uni", "s_sck"))) 

theta_label <- "Mortality Risk\nWithout Any Treatment (\u03b8)"
s_label <- "Spending (s)"
f_label <- "Mortality Risk\nWith Current Spending (f)"

dt %>% ggplot(aes(y =f, x= theta, color = policy)) + 
  geom_line(size = lwdth) +
  geom_abline(slope = 1, lty = "dashed", size = .3, alpha = .6) +
  scale_x_continuous(expand = c(0,0), n.breaks = 3) +
  scale_y_continuous(expand = c(0,0), n.breaks = 3, limits = c(0,1)) +
  scale_color_manual(values = color_scale_values) +
  labs(x = theta_label, y = f_label) +
  ggsave("f_on_theta.pdf", h = 5, w = 5, device = cairo_pdf)  


theme_update(axis.text.y = element_blank())

dt %>% ggplot(aes(y = s, x= theta, color = policy)) + 
  geom_line(size = lwdth) +
  scale_x_continuous(expand = c(0,0), n.breaks = 3) +
  scale_y_continuous(expand = c(0,0), n.breaks = 3) +
  scale_color_manual(values = color_scale_values) +
  labs(x = theta_label, y = s_label) 
ggsave("s_on_theta.pdf", h = 5, w = 5, device = cairo_pdf)  


dt %>% ggplot(aes(y = s, color = policy)) +
  geom_line(aes(x= theta), size = lwdth, lty = "dashed", alpha = .9) +
  geom_line(aes(x= f), size = lwdth) +
  scale_x_continuous(expand = c(0,0), n.breaks = 3) +
  scale_y_continuous(expand = c(0,0), n.breaks = 3) +
  scale_color_manual(values = color_scale_values) +
  labs(x = "f, \u03b8", y = s_label)

ggsave("s_on_f_and_theta.pdf", h = 5, w = 5, device = cairo_pdf)  
  


